package org.lwxyz.tools.mail;

import org.lwxyz.tools.mail.entity.Mail;

import java.io.FileOutputStream;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;

/**
 * @author yuwei
 * @version 1.0-SNAPSHOT
 * @description 邮件发送工具类
 * @date 2018-1-22 15:41:45
 */
public class MailUtils {
    // 初始化邮箱配置数据
    private static String host = MailAuthorize.host;
    private static String email = MailAuthorize.email;
    private static String protocol = MailAuthorize.protocol;
    private static String auth = MailAuthorize.auth;
    private static String username = MailAuthorize.username;
    private static String password = MailAuthorize.password;

    /**
     * 发送邮件
     * @param type
     * @param receive
     * @param mail
     * @return
     * @throws Exception
     */
    public static String sendMail(int type, String receive, Mail mail) throws Exception{
        Properties prop = new Properties();
        prop.setProperty("mail.host", host);
        prop.setProperty("mail.transport.protocol", protocol);
        prop.setProperty("mail.smtp.auth", auth);
        //使用JavaMail发送邮件的5个步骤
        //1、创建session
        Session session = Session.getInstance(prop);
        //开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
        session.setDebug(true);
        //2、通过session得到transport对象
        Transport ts = session.getTransport();
        //3、使用邮箱的用户名和密码连上邮件服务器，发送邮件时，发件人需要提交邮箱的用户名和密码给smtp服务器，用户名和密码都通过验证之后才能够正常发送邮件给收件人。
        ts.connect(host, username, password);

        /**
         *
         */
        //创建邮件对象
        MimeMessage message = new MimeMessage(session);
        //指明邮件的发件人
        message.setFrom(new InternetAddress(email));
        //指明邮件的收件人，现在发件人和收件人是一样的，那就是自己给自己发
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(receive));
        /**
         *
         */

        //4、创建邮件
        Message msg = null;
        switch (type) {
            /**
             * 纯文字
             */
            case 1 : msg = createSimpleMail(message, mail); break;
            /**
             * 带图片
             */
            case 2 : msg = createImageMail(message); break;
            /**
             * 带附件
             */
            case 3 : msg = createAttachMail(message); break;
            /**
             * 带图片+附件
             */
            case 4 : msg = createMixedMail(message); break;
        }
        //5、发送邮件
        ts.sendMessage(msg, msg.getAllRecipients());
        ts.close();
        return "发送成功";
    }

    /**
     * 创建普通纯文字邮件
     * @param message
     * @return
     * @throws Exception
     */
    public static Message createSimpleMail(MimeMessage message, Mail mail)
            throws Exception {
        //邮件的标题
        message.setSubject(mail.getSubject());
        //邮件的文本内容
        message.setContent(mail.getContext(), "text/html;charset=UTF-8");
        //返回创建好的邮件对象
        return message;
    }

    /**
     * 创建带图片的邮件
     * @param message
     * @return
     * @throws Exception
     */
    public static MimeMessage createImageMail(MimeMessage message) throws Exception {
        //邮件标题
        message.setSubject("带图片的邮件");

        // 准备邮件数据
        // 准备邮件正文数据
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("这是一封邮件正文带图片<img src='cid:xxx.jpg'>的邮件", "text/html;charset=UTF-8");
        // 准备图片数据
        MimeBodyPart image = new MimeBodyPart();
        DataHandler dh = new DataHandler(new FileDataSource("src\\1.jpg"));
        image.setDataHandler(dh);
        image.setContentID("xxx.jpg");
        // 描述数据关系
        MimeMultipart mm = new MimeMultipart();
        mm.addBodyPart(text);
        mm.addBodyPart(image);
        mm.setSubType("related");

        message.setContent(mm);
        message.saveChanges();
        //将创建好的邮件写入到E盘以文件的形式进行保存
        // message.writeTo(new FileOutputStream("E:\\ImageMail.eml"));
        //返回创建好的邮件
        return message;
    }

    /**
     * 创建带附件的邮件
     * @param message
     * @return
     * @throws Exception
     */
    public static MimeMessage createAttachMail(MimeMessage message) throws Exception{
        //邮件标题
        message.setSubject("JavaMail邮件发送测试");

        //创建邮件正文，为了避免邮件正文中文乱码问题，需要使用charset=UTF-8指明字符编码
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("使用JavaMail创建的带附件的邮件", "text/html;charset=UTF-8");

        //创建邮件附件
        MimeBodyPart attach = new MimeBodyPart();
        DataHandler dh = new DataHandler(new FileDataSource("src\\2.jpg"));
        attach.setDataHandler(dh);
        attach.setFileName(dh.getName());  //

        //创建容器描述数据关系
        MimeMultipart mp = new MimeMultipart();
        mp.addBodyPart(text);
        mp.addBodyPart(attach);
        mp.setSubType("mixed");

        message.setContent(mp);
        message.saveChanges();
        //将创建的Email写入到E盘存储
        // message.writeTo(new FileOutputStream("E:\\attachMail.eml"));
        //返回生成的邮件
        return message;
    }

    /**
     * 创建同时存在附件和图片的邮件
     * @param message
     * @return
     * @throws Exception
     */
    public static MimeMessage createMixedMail(MimeMessage message) throws Exception {
        message.setSubject("带附件和带图片的的邮件");

        //正文
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("xxx这是女的xxxx<br/><img src='cid:aaa.jpg'>","text/html;charset=UTF-8");

        //图片
        MimeBodyPart image = new MimeBodyPart();
        image.setDataHandler(new DataHandler(new FileDataSource("src\\3.jpg")));
        image.setContentID("aaa.jpg");

        //附件1
        MimeBodyPart attach = new MimeBodyPart();
        DataHandler dh = new DataHandler(new FileDataSource("src\\4.zip"));
        attach.setDataHandler(dh);
        attach.setFileName(dh.getName());

        //附件2
        MimeBodyPart attach2 = new MimeBodyPart();
        DataHandler dh2 = new DataHandler(new FileDataSource("src\\波子.zip"));
        attach2.setDataHandler(dh2);
        attach2.setFileName(MimeUtility.encodeText(dh2.getName()));

        //描述关系:正文和图片
        MimeMultipart mp1 = new MimeMultipart();
        mp1.addBodyPart(text);
        mp1.addBodyPart(image);
        mp1.setSubType("related");

        //描述关系:正文和附件
        MimeMultipart mp2 = new MimeMultipart();
        mp2.addBodyPart(attach);
        mp2.addBodyPart(attach2);

        //代表正文的bodypart
        MimeBodyPart content = new MimeBodyPart();
        content.setContent(mp1);
        mp2.addBodyPart(content);
        mp2.setSubType("mixed");

        message.setContent(mp2);
        message.saveChanges();

        // message.writeTo(new FileOutputStream("E:\\MixedMail.eml"));
        //返回创建好的的邮件
        return message;
    }
}
